package com.example.nowcodercommunity.service;

import com.example.nowcodercommunity.dao.DiscussPostMapper;
import com.example.nowcodercommunity.entity.DiscussPost;
import com.example.nowcodercommunity.util.SensitiveFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.util.HtmlUtils;

import java.util.List;

@Service
public class DiscussPostService {

    @Autowired
    private DiscussPostMapper mapper;

    @Autowired
    private SensitiveFilter filter;

    public DiscussPost findDiscussPostById(int id){
        return mapper.selectDiscussPostById(id);
    }

    public List<DiscussPost> findDiscussPostsWithinUser(int userId,int from,int limit){
        return mapper.selectDiscussPostsWithinUser(userId,from,limit);
    }

    public int findDiscussPostRows(int userId){
        return mapper.selectCountDiscussPostRows(userId);
    }

    public int updateCommentCount(int id,int commentCount){
        return mapper.updateCommentCount(id,commentCount);
    }

    public int addDiscussPost(DiscussPost post){
        if(post==null){
            throw new RuntimeException("添加帖子参数不能为空！");
        }

        // 将对于HTML有意义的标签去除
        String title = post.getTitle();
        title = HtmlUtils.htmlEscape(title);
        title = filter.filter(title);
        post.setTitle(title);

        String content = post.getContent();
        content = HtmlUtils.htmlEscape(content);
        content = filter.filter(content);
        post.setContent(content);

        return mapper.insertDiscussPost(post);
    }
}
